{{define "title"}}
Wireguard Server
{{end}}

{{define "top_css"}}
{{end}}

{{define "username"}}
{{ .username }}
{{end}}

{{define "page_title"}}
Wireguard Server Settings
{{end}}

{{define "page_content"}}
<section class="content">
    <div class="container-fluid">
        <!-- <h5 class="mt-4 mb-2">Wireguard Server</h5> -->
        <div class="row">
            <!-- left column -->
            <div class="col-md-6">
                <div class="card card-success">
                    <div class="card-header">
                        <h3 class="card-title">Interface</h3>
                    </div>
                    <!-- /.card-header -->
                    <!-- form start -->
                    <form role="form" id="frm_server_interface" name="frm_server_interface">
                        <div class="card-body">
                            <div class="form-group">
                                <label for="addresses" class="control-label">Server Interface Addresses</label>
                                <input type="text" data-role="tagsinput" class="form-control" id="addresses" value="">
                            </div>
                            <div class="form-group">
                                <label for="listen_port">Listen Port</label>
                                <input type="text" class="form-control" id="listen_port" name="listen_port"
                                    placeholder="Listen Port" value="{{ .serverInterface.ListenPort }}">
                            </div>
                            <div class="form-group">
                                <label for="post_up">Post Up Script</label>
                                <input type="text" class="form-control" id="post_up" name="post_up"
                                       placeholder="Post Up Script" value="{{ .serverInterface.PostUp }}">
                            </div>
                            <div class="form-group">
                                <label for="pre_down">Pre Down Script</label>
                                <input type="text" class="form-control" id="pre_down" name="pre_down"
                                       placeholder="Pre Down Script" value="{{ .serverInterface.PreDown }}">
                            </div>

                            <div class="form-group">
                                <label for="post_down">Post Down Script</label>
                                <input type="text" class="form-control" id="post_down" name="post_down"
                                       placeholder="Post Down Script" value="{{ .serverInterface.PostDown }}">
                            </div>
                        </div>
                        <!-- /.card-body -->

                        <div class="card-footer">
                            <button type="submit" class="btn btn-success">Save</button>
                        </div>
                    </form>
                </div>
                <!-- /.card -->
            </div>
            <!-- right column -->
            <div class="col-md-6">
                <div class="card card-danger">
                    <div class="card-header">
                        <h3 class="card-title">Key Pair</h3>
                    </div>
                    <!-- /.card-header -->
                    <!-- form start -->
                    <form role="form">
                        <div class="card-body">
                            <div class="form-group">
                                <label for="private_key">Private Key</label>
                                <div class="input-group input-group">
                                    <input type="password" class="form-control" id="private_key" placeholder="Private Key"
                                        value="{{ .serverKeyPair.PrivateKey }}" disabled>
                                    <span class="input-group-append">
                                        <button type="button" class="btn btn-danger btn-flat"
                                            id="btn_show_private_key">Show</button>
                                    </span>
                                </div>
                            </div>
                            <div class="form-group">
                                <label for="public_key">Public Key</label>
                                <input type="text" class="form-control" id="public_key" placeholder="Public Key"
                                    value="{{ .serverKeyPair.PublicKey }}" disabled>
                            </div>
                        </div>
                        <!-- /.card-body -->

                        <div class="card-footer">
                            <button type="button" class="btn btn-danger" data-toggle="modal"
                                data-target="#modal_keypair_confirmation">Generate</button>
                        </div>
                    </form>
                </div>
                <!-- /.card -->
            </div>
        </div>
        <!-- /.row -->
    </div>
</section>

<div class="modal fade" id="modal_keypair_confirmation">
    <div class="modal-dialog">
        <div class="modal-content bg-warning">
            <div class="modal-header">
                <h4 class="modal-title">KeyPair Generation</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <p>Are you sure to generate a new key pair for the Wireguard server?<br/>
                The existing Client's peer public key need to be updated to keep the connection working.</p>
            </div>
            <div class="modal-footer justify-content-between">
                <button type="button" class="btn btn-outline-dark" data-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-outline-dark" id="btn_generate_confirm">Generate</button>
            </div>
        </div>
        <!-- /.modal-content -->
    </div>
    <!-- /.modal-dialog -->
</div>
<!-- /.modal -->
{{end}}

{{define "bottom_js"}}
    <script>
        function submitServerInterfaceSetting() {
            const addresses = $("#addresses").val().split(",");
            const listen_port = $("#listen_port").val();
            const post_up = $("#post_up").val();
            const pre_down = $("#pre_down").val();
            const post_down = $("#post_down").val();
            const data = {"addresses": addresses, "listen_port": listen_port, "post_up": post_up, "pre_down": pre_down, "post_down": post_down};

            $.ajax({
                cache: false,
                method: 'POST',
                url: '{{.basePath}}/wg-server/interfaces',
                dataType: 'json',
                contentType: "application/json",
                data: JSON.stringify(data),
                success: function(data) {
                    $("#modal_new_client").modal('hide');
                    toastr.success('Updated Wireguard server interface addresses successfully');
                },
                error: function(jqXHR, exception) {
                    const responseJson = jQuery.parseJSON(jqXHR.responseText);
                    toastr.error(responseJson['message']);
                }
            });
        }
    </script>
    <script>
        // Wireguard Interface Addresses tag input
        $("#addresses").tagsInput({
            'width': '100%',
            // 'height': '75%',
            'interactive': true,
            'defaultText': 'Add More',
            'removeWithBackspace': true,
            'minChars': 0,
            'minInputWidth': '100%',
            'placeholderColor': '#666666'
        });

        // Load server addresses to the form
        {{range .serverInterface.Addresses}}
        $("#addresses").removeTag('{{.}}');
        $("#addresses").addTag('{{.}}');
        {{end}}

        // Wireguard Interface Addresses form validation
        $(document).ready(function () {
            $.validator.setDefaults({
                submitHandler: function () {
                    submitServerInterfaceSetting();
                }
            });
            $("#frm_server_interface").validate({
                rules: {
                    listen_port: {
                        required: true,
                        digits: true,
                        range: [1, 65535]
                    }
                },
                messages: {
                    listen_port: {
                        required: "Please enter a port",
                        digits: "Port must be an integer",
                        range: "Port must be in range 1..65535"
                    }
                },
                errorElement: 'span',
                errorPlacement: function (error, element) {
                    error.addClass('invalid-feedback');
                    element.closest('.form-group').append(error);
                },
                highlight: function (element, errorClass, validClass) {
                    $(element).addClass('is-invalid');
                },
                unhighlight: function (element, errorClass, validClass) {
                    $(element).removeClass('is-invalid');
                }
            });
        });

        // Wireguard Key Pair generation confirmation button
        $(document).ready(function () {
            $("#btn_generate_confirm").click(function () {
                $.ajax({
                    cache: false,
                    method: 'POST',
                    url: '{{.basePath}}/wg-server/keypair',
                    dataType: 'json',
                    contentType: "application/json",
                    success: function(data) {
                        $("#modal_keypair_confirmation").modal('hide');
                        toastr.success('Generate new key pair successfully');
                        // update the UI
                        $("#private_key").val(data['private_key']);
                        $("#public_key").val(data['public_key']);
                    },
                    error: function(jqXHR, exception) {
                        const responseJson = jQuery.parseJSON(jqXHR.responseText);
                        toastr.error(responseJson['message']);
                    }
                });
            });
        });

        // Show private key button event
        $(document).ready(function () {
            $("#btn_show_private_key").click(function () {
                const privateElement = document.getElementById("private_key");
                const btnElement = document.getElementById("btn_show_private_key");
                if (privateElement.type === 'password') {
                    privateElement.type = 'text';
                    btnElement.innerText = 'Hide';
                } else {
                    privateElement.type = 'password';
                    btnElement.innerText = 'Show';
                }
            });
        });
    </script>
{{end}}
